class Snake {
    head: HTMLElement;
    bodies: HTMLCollection;
    element: HTMLElement;

    constructor() {
        this.element = document.getElementById('snake') as HTMLElement;
        this.head = document.querySelector('#snake > div') as HTMLElement;
        this.bodies = this.element?.getElementsByTagName('div') as HTMLCollection;
    }

    get x() {
        return this.head.offsetLeft;
    }
    get y() {
        return this.head.offsetTop;
    }

    set x(val) {
        this.moveBody();
        this.head.style.left = val + 'px';
        this.checkEatSelf()
    }
    set y(val) {
        this.moveBody();
        this.head.style.top = val + 'px';
        this.checkEatSelf()
    }

    moveBody() {
        for (let i = this.bodies.length - 1; i > 0; i--) {
            const preElement = this.bodies[i - 1] as HTMLElement;
            const curElement = <HTMLElement>this.bodies[i]
            let x = preElement.offsetLeft;
            let y = preElement.offsetTop;
            curElement.style.left = x + 'px';
            curElement.style.top = y + 'px';
        }
    }

    checkEatSelf() {
        for (let i = 1; i < this.bodies.length; i++) {
            const curElement = <HTMLElement>this.bodies[i]
            let x = curElement.offsetLeft;
            let y = curElement.offsetTop;
            if (x === this.x && y === this.y) {
                throw new Error('咬到自己了')
            }
        }
    }

    addBody() {
        const div = document.createElement('div')
        this.element.append(div)
    }
}

export default Snake;
